using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using ICSharpCode.SharpZipLib.Zip;

using Krystalware.SlickUpload;
using Krystalware.SlickUpload.Providers;

namespace Adge.WebControls
{
    /// <summary>
    /// An <see cref="IUploadStreamProvider" /> that streams each file into its own .zip file.
    /// </summary>
    public class ZipUploadStreamProvider : IUploadStreamProvider
    {
        public Stream GetInputStream(UploadedFile file)
        {
            FileStream fileS = null;
            ZipInputStream zipS = null;

            try
            {
                string path = GetZipPath(file);

                fileS = File.OpenRead(path);
                zipS = new ZipInputStream(fileS);

                zipS.GetNextEntry();

                return zipS;
            }
            catch
            {
                if (fileS != null)
                    fileS.Dispose();

                if (zipS != null)
                    zipS.Dispose();

                return null;
            }
        }

        public Stream GetOutputStream(UploadedFile file)
        {
            FileStream fileS = null;
            ZipOutputStream zipS = null;

            try
            {
                string path = GetZipPath(file);

                fileS = File.OpenWrite(path);
                zipS = new ZipOutputStream(fileS);

                zipS.SetLevel(5);

                zipS.PutNextEntry(new ZipEntry(file.ClientName));

                return zipS;
            }
            catch
            {
                if (fileS != null)
                    fileS.Dispose();

                if (zipS != null)
                    zipS.Dispose();

                return null;
            }
        }

        public void RemoveOutput(UploadedFile file)
        {
            string path = GetZipPath(file);

            if (File.Exists(path))
                File.Delete(path);
        }

        string GetZipPath(UploadedFile file)
        {
            return Path.Combine(HttpContext.Current.Server.MapPath("~/Files/"), Path.GetFileNameWithoutExtension(file.ClientName) + ".zip");
        }
    }


}
